package com.utils;

import com.enumeration.JwtExceptionEnum;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.log4j.Log4j2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * JWTUtil.java
 * JSON Web Token
 *
 * @author Liang 649355204@qq.com
 * CreateTime 2019/7/16 8:37
 */
@Log4j2
public class JwtUtil {
    private static Logger logger = LoggerFactory.getLogger(JwtUtil.class);

    /**
     * 过期时间
     */
    public static final long EXPIRE_TIME = 60 * 60 * 60 * 1000;
    /**
     * 刷新时间
     */
    public static final long REFRESH_TIME = 3 * 60 * 60 * 60 * 1000;
    /**
     * 刷新时间
     */
    public static final String SECRET = "dO9OPjvaYOUWoubg6o79HhsWe";

    /**
     * 生成签名，过期时间由EXPIRE_TIME指定
     *
     * @param uuid 用户主键
     * @return token
     */
    public static String createToken(String uuid) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            return JWT.create()
                    // 附加用户信息
                    .withClaim("uuid", uuid)
                    // 附加刷新时间
                    .withClaim("refreshTime", new Date(System.currentTimeMillis() + REFRESH_TIME))
                    // 过期时间
                    .withExpiresAt(date)
                    //签名
                    .sign(algorithm);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 校验token正确性
     */
    public static int verify(String token, String uuid) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("uuid", uuid)
                    .build();
            verifier.verify(token);
            return JwtExceptionEnum.JWT_MATCH.getCode();
        } catch (TokenExpiredException e) {
            logger.debug("TokenExpiredException");
            return JwtExceptionEnum.JWT_EXPIRE.getCode();
        } catch (Exception e) {
            logger.debug("verify异常");
            e.printStackTrace();
            return JwtExceptionEnum.JWT_NOT_MATCH.getCode();
        }
    }

    public static String getUuid(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("uuid").asString();
        } catch (JWTDecodeException e) {
            e.printStackTrace();
            return "";
        }
    }

    public static Date getRefreshTime(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("refreshTime").asDate();
        } catch (JWTDecodeException e) {
            e.printStackTrace();
            return null;
        }
    }
}
